import React,{Component} from "react";
import {withRouter} from "react-router-dom";
import { DatePicker, message, Input, Select, Button, Checkbox, Switch } from 'antd';
import $ from "jquery";
import ajax from "../ajaxMethod";

import CityTables from "../containers/cityTables";
import "../assets/stylesheets/searchBannerS.css";
import moment from 'moment';

const format = "YYYY-MM-DD";

class SearchBannerS extends Component{
    constructor(props){
        super(props);
        this.state={
            //如果父组件有传进来值将传进来的值合并，覆盖本来的值
            initalValues:(()=>{
                if(this.props.initalValues){
                    sessionStorage.setItem("searchValues",  JSON.stringify({initalValues: this.props.initalValues}));
                    return this.props.initalValues;
                }
                else{
                    let values = {
                        trip:"0",//默认单程
                        goCity:"西安",
                        toCity:"北京",
                        goDate:moment().format(format),
                        toDate:moment().format(format),
                        classType:"0",
                        checkChild: false,
                        checkBaby: false
                    };
                    sessionStorage.setItem("searchValues",  JSON.stringify({initalValues: values}));
                    return values;
                }
            })(),
            UIstate:{
                goBoxDisplay:"none",
                toBoxDisplay:"none",
            },
        }   
    }
    componentDidMount(){
        let _this = this;
        if(this.props.onRef){ //给父组件
            this.props.onRef(this.getData); 
        }
        if(this.props.onSelectTrip){//初始化的时候重置一下往返
            this.props.onSelectTrip(this.state.initalValues.trip);
        }
        this.getData();
        //收起展开的输入框
        window.addEventListener("click",function(){
            _this.setState({UIstate:{..._this.state.UIstate, toBoxDisplay: "none", goBoxDisplay: "none"}});
        });
    }
    componentWillUnmount(){//刷新不会触发这个
        console.log("searchBS-unmount卸载了");
    }
    getData = (values) =>{
        let nowValues = values || this.state.initalValues, 
            date = nowValues.goDate,
            goCity = nowValues.goCity,
            toCity = nowValues.toCity,
            _this = this;

        if(this.props.bookState === "1" && this.state.initalValues.trip === "1"){
            //如果直接是第二程的重新查询，查询返程
            date = nowValues.toDate;
            goCity = nowValues.toCity;
            toCity = nowValues.goCity;
        }
        if(values){
            if(values.bookState === "1"){
                //返程的查询
                date = nowValues.toDate;
                goCity = nowValues.toCity;
                toCity = nowValues.goCity;
            }
        }
        ajax.getAjax("/interface/search", {
            goCity: goCity,
            toCity: toCity,
            date: date,
            classType: nowValues.classType,
            checkChild: nowValues.checkChild,
            checkBaby: nowValues.checkBaby
        }, res=>{
            if(res.success){
                _this.props.onGetData(res.data);
            }else{
                console.error("res-err",res);
            }
        },err=>{
            console.error(err);
        })
    }
    //出发地//目的地
    getGoCityNames = (citys) =>{ this.setState({goCitys:citys}); }
    getToCityNames = (citys) =>{ this.setState({toCitys:citys}); }
    onSelectTrip = (value) =>{
        //往返,设置返回日期
        this.props.onSelectTrip(value);
        if(value === "1"){//往返
            let dates = this.getNowDate(),
                maxymd = dates.maxymd,
                toDate = this.state.initalValues.toDate,
                nowToDate = toDate,
                goDate = this.state.initalValues.goDate,
                nnextDate = moment(goDate).add(2, 'd').format(format),//后推2天
                nextDate = moment(goDate).add(1, 'd').format(format);//后推1天

            //返回日期是空的时候或者小于出发日期计算当前选中日期往后2天的是否可选择,否则退后一天,否则只有选中的这一天
            if(!this.state.initalValues.toDate || toDate <= goDate){
                if(maxymd >= nextDate){
                    nowToDate = nextDate;
                }else if(maxymd >= nextpreDate.format(format)){
                    nowToDate = nnextDate;
                }else{
                    nowToDate = goDate;
                }
                this.setState({initalValues: {...this.state.initalValues, toDate: nowToDate, trip: value}});
                sessionStorage.setItem("searchValues",  JSON.stringify({initalValues: {...this.state.initalValues, toDate: nowToDate, trip: value}}));
            }else{
                //返回的日期不需要处理，只要设置选择类型就行
                this.setState({initalValues: {...this.state.initalValues, trip: value}});
                sessionStorage.setItem("searchValues",  JSON.stringify({initalValues: {...this.state.initalValues, trip: value}}));
            }
        }else{//单程
            this.setState({initalValues:{...this.state.initalValues, trip: value}});
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, trip: value}}));
        }
    }
    onGoCityClick  = (e) =>{
        this.setState({UIstate:{...this.state.UIstate, toBoxDisplay: "none", goBoxDisplay: "block"}});
        //阻止本身冒泡
        e.nativeEvent.stopImmediatePropagation(); 
    }
    onToCityClick  = (e) =>{
        this.setState({UIstate:{...this.state.UIstate, toBoxDisplay: "block", goBoxDisplay: "none"}});
        e.nativeEvent.stopImmediatePropagation(); //阻止事件
    }
    onGoCityInput = (e) =>{
        let goBoxDisplay = "";
        e.target.value !== ""?goBoxDisplay ="none":goBoxDisplay = "block";
        this.setState({
            UIstate:{...this.state.UIstate, goBoxDisplay: goBoxDisplay},
            initalValues:{...this.state.initalValues, goCity: e.target.value}
        });
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goCity: e.target.value}}));
    }
    onToCityInput = (e) =>{
        let toBoxDisplay = "";
        e.target.value !== ""? toBoxDisplay = "none":toBoxDisplay = "block";
        this.setState({
            UIstate:{...this.state.UIstate, toBoxDisplay: toBoxDisplay},
            initalValues:{...this.state.initalValues, toCity: e.target.value}
        });
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, toCity: e.target.value}}));
    }
    getGoCityName = (e) =>{
        this.setState({
            UIstate:{...this.state.UIstate, goBoxDisplay: "none"},
            initalValues:{...this.state.initalValues, goCity: e.target.innerText}
        });
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goCity: e.target.innerText}}));
    }
    getToCityName = (e) =>{
        this.setState({
            UIstate:{...this.state.UIstate, toBoxDisplay: "none"},
            initalValues:{...this.state.initalValues, toCity: e.target.innerText}
        });
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, toCity: e.target.innerText}}));
    }
    exchangeCity = () =>{
        let goCity = this.state.initalValues.goCity,
            toCity = this.state.initalValues.toCity;
        this.setState({
            initalValues:{...this.state.initalValues, goCity: toCity, toCity: goCity}
        });
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goCity: toCity, toCity: goCity}}));
    }
    //选择日期
    onCalendarChange = (value, dateString) =>{
        if(this.state.initalValues.trip === "1"){
            //是往返的，如果返回日期大于出发日期不用修改，否则往后推
            let dates = this.getNowDate(),
                maxymd = dates.maxymd,
                initalValues = this.state.initalValues,
                toDate = initalValues.toDate,
                nnextDate = moment(value.format(format)).add(2, 'd').format(format),
                nextDate = moment(value.format(format)).add(1, 'd').format(format);
            //如果返回日期不存在|返回日期小于出发日期
            if( !initalValues.toDate || initalValues.toDate < value){
                if(nextDate.format(format) <= maxymd){//多2天是否超出范围
                    toDate = nnextDate;
                }else if(nnextDate.format(format) <= maxymd){//多1天是否超出范围
                    toDate = nextDate;
                }else{
                    toDate = value.format(format);
                }
                this.setState({initalValues:{...this.state.initalValues, goDate: value.format(format), toDate: toDate}});
                sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: value.format(format), toDate: toDate}}));
            }else{//返回大于今天就不管
                this.setState({initalValues:{...this.state.initalValues, goDate: value.format(format)}});
                sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: value.format(format)}}));
            }
        }else{//单程
            this.setState({initalValues:{...this.state.initalValues, goDate: value.format(format)}}); 
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: value.format(format)}}));
        }
    }
    onBackCalendarChange = (value, dateString) =>{
        console.log("onBackCalendarChange", value);
        this.setState({initalValues:{...this.state.initalValues, toDate: value.format(format)}});
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, toDate: value.format(format)}}));
    }
    //不能点击的日期
    disabledDate = (current) =>{
        let dates = this.getNowDate();  
        return  current.format('YYYY-MM-DD') < dates.ymd || current.format('YYYY-MM-DD') > dates.maxymd;
    }
    disabledBackDate = (current) =>{
        let dates = this.getNowDate();  
        return  current.format('YYYY-MM-DD') < this.state.initalValues.goDate || current.format('YYYY-MM-DD') > dates.maxymd;
    }
    //舱型选择
    onSelect = (value, opt)=>{ 
        this.setState({initalValues:{...this.state.initalValues, classType: value}}); 
        sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, classType: value}}));
    }
    
    onPreday = (e) =>{
        //边界是今天
        let dates = this.getNowDate(),
            ymd = dates.ymd,
            goDate = this.state.initalValues.goDate,
            preDate = moment(goDate).subtract(1, 'd').format(format);//前移一天

        if(preDate>= ymd){
            this.setState({initalValues:{...this.state.initalValues, goDate: preDate}}); 
            this.getData({...this.state.initalValues, goDate: preDate});
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: preDate}}));
        }
    }
    onNextday = (e) =>{
        //边界是今天+30天
        let dates = this.getNowDate(),
            maxymd = dates.maxymd,
            initalValues = this.state.initalValues,
            goDate = this.state.initalValues.goDate,
            toDate = this.state.initalValues.toDate,
            nextDate = moment(goDate).add(1, 'd').format(format),//后推一天
            nnextDate = moment(goDate).add(2, 'd').format(format),//后推2天
            nnnextDate = moment(goDate).add(3, 'd').format(format);//后推3天
        
        if(nextDate <= maxymd){ 
            
            //如果是往返（trip="1"）的检查返回日期是不存在|小于今天，就设置为大于的,先看后2天是否超过范围，否则看后一天，否则就是今天
            if(initalValues.trip === "1"){
                console.log("去程是否没有填或者比返程小了", initalValues.toDate < nextDate, initalValues.toDate, nextDate);
                if(!initalValues.toDate || initalValues.toDate < nextDate){
                    if(nnnextDate< maxymd){//往后2天
                        toDate = nnnextDate;
                    }else if(nnextDate < maxymd){//往后一天
                        toDate = nnextDate;
                    }else{//今天
                        toDate = nextDate;
                    }
                    this.setState({initalValues:{...this.state.initalValues, goDate: nextDate, toDate: toDate}});
                    sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: nextDate, toDate: toDate}}));
                    //强制刷新
                    this.getData({...this.state.initalValues, goDate: nextDate, toDate: toDate});
                    this.forceUpdate();
                }else{//返回大于今天就不管
                    this.setState({initalValues:{...this.state.initalValues, goDate: nextDate}});
                    this.getData({...this.state.initalValues, goDate: nextDate});
                    sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: nextDate}}));
                }
            }
            else{
                this.setState({initalValues:{...this.state.initalValues, goDate: nextDate}});
                this.getData({...this.state.initalValues, goDate: nextDate});
                sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, goDate: nextDate}}));
            }
        }
    }
    getNowDate = () =>{
        //获取当前日期的字符串和30天之后的日期字符串
        let date = moment(),//当前年月日，字符串
            nextDate = moment().add(30, 'd'),//30天后的日期
            res = {};
        res.ymd = date.format(format);
        res.maxymd = nextDate.format(format);
        return res;
    }
    handleChildChange = (e) =>{ 
        if(this.state.initalValues.checkChild){
            this.setState({initalValues:{...this.state.initalValues, checkChild: false}});
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, checkChild: false}}));
        }else{
            this.setState({initalValues:{...this.state.initalValues, checkChild: true}}); 
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, checkChild: true}}));
        }
    }
    handleBabyChange = (e) =>{ 
        if(this.state.initalValues.checkBaby){
            this.setState({initalValues:{...this.state.initalValues, checkBaby: false}});
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, checkBaby: false}}));
        }else{
            this.setState({initalValues:{...this.state.initalValues, checkBaby: true}}); 
            sessionStorage.setItem("searchValues",  JSON.stringify({initalValues:{...this.state.initalValues, checkBaby: true}}));
        }
    }
    onSubmit = (e) =>{
        e.preventDefault(); 
        // 0:成功查询,1:出发地点不存在，2:到达地点不存在，3:出发地点为空，4:到达地点为空,5:出发地点和到达地点不能相同，6:出发日期为空7:返回日期为空。
        //所有字符去掉前后空格,重新查询的时候bookState要改变的
        let state = 0;
        let values = this.state.initalValues;
        let regExp = /\s/g;
        // /^\s*(.*?)\s*$/;
        const path = {pathname: '/search', values: values};

        if(!values.goCity){ state = 3; }
        else{ 
            let goCity = values.goCity.replace(regExp, ""),
                go = this.goCityIn(goCity);
            if(!go){ state = 1; }
        }
        if(!values.toCity){ state = 4; }
        else{
            let toCity = values.toCity.replace(regExp, ""),
                to = this.toCityIn(toCity);
            if(!to){ state = 2; }
            else{ if(values.goCity === values.toCity){ state = 5; } }
        }
        if(!values.goDate){ state = 6; }
        if(values.trip === "1"){ if(!values.toDate){ state = 7; } }
        console.log("查询的状态",state, values);
        switch(state){
            case 0:
            {
                //根据条件获取航班信息
                this.getData(values);
            }break;
            case 1:
            message.error("出发地点不存在");break;
            case 2:
            message.error("到达地点不存在");break;
            case 3:
            message.error("出发地点为空");break;
            case 4:
            message.error("到达地点为空");break;
            case 5:
            message.error("出发地点和到达地点不能相同");break;
            case 6:
            message.error("出发日期为空");break;
            case 7:
            message.error("返回日期为空");break;
            default:
        }
    }
    goCityIn = (city) =>{
        let goCitys = this.state.goCitys;
        let flag = false;
        for(let item in goCitys){
            if(goCitys[item].indexOf(city) !== -1){
                flag = true;
                break;
            }
        }
        return flag;
    }
    toCityIn = (city) =>{
        let toCitys = this.state.toCitys;
        let flag = false;
        for(let item in toCitys){
            if(toCitys[item].indexOf(city) !== -1){
                flag = true;
                break;
            }
        }
        return flag;
    }

    render(){
        const initalValues = this.state.initalValues;
        const UIstate = this.state.UIstate;
        console.log("searchBannerS-state", this.state);
        //这个有什么用????
        sessionStorage.setItem("searchValues", JSON.stringify(this.state.initalValues));
        return (
        <div id="index-search-s">
        {/*  action="/search"*/}
            <form method="get" onSubmit={this.onSubmit}>
                <div className="s-box">
                    <div className="s-c0">
                        <Select value={initalValues.trip === undefined?"0":initalValues.trip} className="select" onSelect={this.onSelectTrip}>
                            <Select.Option value="0">单程</Select.Option>
                            <Select.Option value="1">往返</Select.Option>
                        </Select>
                    </div>
                    <div className="s-c1">
                        <div className="s-left">
                            <Input id="goCity-s" name="goCity" value={this.state.initalValues.goCity} autocomplete="off" onInput={this.onGoCityInput} onClick={this.onGoCityClick}></Input>
                            <div id="go-city-s" style={{display:UIstate.goBoxDisplay}}>
                                <CityTables getCityName={this.getGoCityName} getCityNames={this.getGoCityNames}></CityTables>
                            </div>
                        </div>
                        <div className="img-block" onClick={this.exchangeCity}><img src={require("../assets/images/change.png")} className="change-icon"></img></div>
                        <div className="s-right">
                            <Input id="toCity-s" name="toCity" value={this.state.initalValues.toCity} autocomplete="off" onInput={this.onToCityInput} onClick={this.onToCityClick}></Input>
                            <div id="to-city-s" style={{display:UIstate.toBoxDisplay}}>
                                <CityTables getCityName={this.getToCityName} getCityNames={this.getToCityNames} ></CityTables>
                            </div>
                        </div>
                    </div>
                    <div className="s-c2">
                        <Button onClick={this.onPreday}>{"<"}</Button>
                        <div className="s-left">
                            {/* 只能选择今天到之后30天，总共31天的日期 */}
                            <DatePicker id="goDate-s"  value={moment(initalValues.goDate)} format={format} placeholder="出发日期" disabledDate={this.disabledDate} onChange={this.onCalendarChange}></DatePicker>
                        </div>
                        <Button onClick={this.onNextday}>{">"}</Button>
                        <div>
                            {/* {console.log("initalValues.toDate和render的state值不一样", initalValues.toDate.format(format))} */}
                            <DatePicker id="backDate-s" value={moment(initalValues.toDate)}  format={format} placeholder="返回日期" disabledDate={this.disabledBackDate} onChange={this.onBackCalendarChange}></DatePicker>
                        </div>
                        <div className="s-right">
                            <Select value={initalValues.classType} className="select" onSelect={this.onSelect}>
                                <Select.Option value="0">不限</Select.Option>
                                <Select.Option value="1">经济舱</Select.Option>
                                <Select.Option value="2">商务舱</Select.Option>
                                <Select.Option value="3">头等舱</Select.Option>
                            </Select>
                        </div>
                    </div>
                    <div className="s-c3">
                        <div>
                            <Checkbox id="child-s" value="child" name="child" onChange={this.handleChildChange} checked={initalValues.checkChild}></Checkbox><span>带儿童</span>
                        </div>
                        <div><Checkbox id="baby-s" value="baby" name="baby" onChange={this.handleBabyChange} checked={initalValues.checkBaby}></Checkbox><span>带婴儿</span></div>
                    </div>
                    <Button type="primary" htmlType="submit">重新查询</Button>
                    {/* <Button onClick={this.onSubmit}>重新查询</Button> */}
                </div>
            </form>
        </div>
        )
    }
}

export default withRouter(SearchBannerS);

